/* vim:ft=objc:
 * $Id: Shell.m 114 2005-05-12 05:15:40Z bmoore $
 *
 * Copyright (c) 2004, 2005  Branden J. Moore.
 *
 * This file is part of MacBiff, and is free software; you can redistribute
 * it and/or modify it under the terms of the GNU General Public License
 * version 2 as published by the Free Software Foundation.
 *
 * MacBiff is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with MacBiff; if not, write to the Free Software Foundation, Inc., 59
 * Temple Place, Suite 330, Boston, MA  02111-1307 USA.
 *
 */

#import <errno.h>
#import <Cocoa/Cocoa.h>
#import "Shell.h"

#import <MacBiffPlugIn/PreferencesController.h>
#import <MacBiffPlugIn/debug.h>
#import <MacBiffPlugIn/Folder.h>

#define APP_NAME @"MacBiff"
#define PLUGIN_NAME @"Shell Command"

@implementation Shell

+ (NSString*) plugInName
{
	return PLUGIN_NAME;
}

+ (NSString*) plugInVersion
{
	return @"1.0.0";
}

+ (NSString*) plugInAuthor
{
	return @"Branden J. Moore <bmoore@forkit.org>";
}

+ (NSString*) plugInUrl
{
	return @"http://www.forkit.org/macbiff/";
}


- (id) init
{
	dprintf("Initializing Shell PlugIn.\n");
	if ( ( self = [super init] ) != Nil ) {

		dprintf("Loading Shell's NIB.\n");
		if ( ![NSBundle loadNibNamed: @"Shell" owner: self] ) {
			alert("Unable to load Shell's Nib\n");
			return nil;
		}
	}
	return self;
}


- (void) dealloc
{
	[super dealloc];
}



- (void) setupView
{
	NSDictionary *plugPrefs = Nil;

	dprintf("Setting up the View for Shell.\n");

	plugPrefs = [prefs action: PLUGIN_NAME];

	[perFolderButton setState:
		[[plugPrefs objectForKey: @"Per Folder"] boolValue] ?
			NSOnState : NSOffState];

	[preStringField setStringValue:
		[plugPrefs objectForKey: @"Pre Command"]];
	[postStringField setStringValue:
		[plugPrefs objectForKey: @"Post Command"]];
}

- (void) doCommandOnAccount: (Account*) acct perFolder: (BOOL) per_folder;
{
	NSString *actStr = Nil;
	NSMutableString *cmd = Nil;
	NSArray *folders = Nil;
	unsigned int i;

	actStr = [self buildStringFromAccount: acct];
	if ( !per_folder ) {
		folders = [NSArray arrayWithObject: @""];
	} else {
		folders = [acct foldersWithNewMailIncludingMasked: NO];
	}

	for ( i = 0 ; i < [folders count] ; ++i ) {
		cmd = [NSMutableString stringWithCapacity: [actStr length]];
		[cmd replaceOccurrencesOfString: @"%d"
			withString: [[folders objectAtIndex: i] name]
			options: NSLiteralSearch
			range: NSMakeRange(0, [cmd length])];

		dprintf("About to Exec '%s'\n", [cmd cString]);
		if ( system([cmd cString]) ) {
			alert("Shell PlugIn Error: %s\n", strerror(errno));
		}
	}
}

- (void) preActionForAccount: (Account*)acct
{
	[self doCommandOnAccount: acct perFolder: NO];
}


- (void) postActionForAccount: (Account*)acct
{
	NSArray *newMailFolders = [acct foldersWithNewMailIncludingMasked: NO];

	if ( [newMailFolders count] == 0 ) return;

	[self doCommandOnAccount: acct perFolder: [[[prefs action: PLUGIN_NAME]
			objectForKey: @"Per Folder"] boolValue]];
}


- (IBAction) setPerFolder: (id) sender
{
	[[prefs action: PLUGIN_NAME] setObject: [NSNumber numberWithBool:
			([perFolderButton state] == NSOnState)]
		forKey: @"Per Folder"];
	[prefs commitActions];
}


- (IBAction) setPreString: (id) sender
{
	[[prefs action: PLUGIN_NAME] setObject:
			[preStringField stringValue]
		forKey: @"Pre Command"];
	[prefs commitActions];

}

- (IBAction) setPostString: (id) sender
{
	[[prefs action: PLUGIN_NAME] setObject:
			[postStringField stringValue]
		forKey: @"Post Command"];
	[prefs commitActions];

}


- (NSString*) buildStringFromAccount: (Account*) acct
{
/*
 * Preference String Format:
 *
 * %a : Account Name
 * %n : # New Messages
 * %u : # Unread Messages
 * %t : Total # of Messages
 * %F : # of folders with Unread Messages
 * %f : # of folders with New Messages
 * %L : List of folders with Unread Messages
 * %l : List of folders with New Messages
 */
	NSRange range;
	NSMutableString *str = [NSMutableString stringWithCapacity: 32];
	NSMutableString *flist = [NSMutableString stringWithCapacity: 32];
	NSArray *arr;
	unsigned int i;

	[str setString: [[prefs action: PLUGIN_NAME] objectForKey: @"String"]];

	range = NSMakeRange(0, [str length]);
	[str replaceOccurrencesOfString: @"%a" withString: [acct name]
		options: NSLiteralSearch range: range];

	range = NSMakeRange(0, [str length]);
	[str replaceOccurrencesOfString: @"%n"
		withString: [NSString stringWithFormat: @"%u", [acct new]]
		options: NSLiteralSearch range: range];

	range = NSMakeRange(0, [str length]);
	[str replaceOccurrencesOfString: @"%u"
		withString: [NSString stringWithFormat: @"%u", [acct unread]]
		options: NSLiteralSearch range: range];

	range = NSMakeRange(0, [str length]);
	[str replaceOccurrencesOfString: @"%t"
		withString: [NSString stringWithFormat: @"%u", [acct total]]
		options: NSLiteralSearch range: range];

	range = NSMakeRange(0, [str length]);
	[str replaceOccurrencesOfString: @"%F"
			     withString: [NSString stringWithFormat: @"%u",
				[[acct foldersWithUnreadMailIncludingMasked: NO]
					count]]
		options: NSLiteralSearch range: range];

	range = NSMakeRange(0, [str length]);
	[str replaceOccurrencesOfString: @"%f"
			     withString: [NSString stringWithFormat: @"%u",
				[[acct foldersWithNewMailIncludingMasked: NO]
					count]]
		options: NSLiteralSearch range: range];

	[flist setString: @""];
	arr = [acct foldersWithUnreadMailIncludingMasked: NO];
	if ( [arr count] > 0 ) {
		[flist setString: [[arr objectAtIndex: 0] name]];
		for ( i = 1 ; i < [arr count] ; ++i )
			[flist appendFormat: @", %@", [[arr objectAtIndex: i] name]];

	}
	range = NSMakeRange(0, [str length]);
	[str replaceOccurrencesOfString: @"%L"
		withString: flist options: NSLiteralSearch range: range];

	[flist setString: @""];
	arr = [acct foldersWithNewMailIncludingMasked: NO];
	if ( [arr count] > 0 ) {
		[flist setString: [[arr objectAtIndex: 0] name]];
		for ( i = 1 ; i < [arr count] ; ++i )
			[flist appendFormat: @", %@", [[arr objectAtIndex: i] name]];

	}
	range = NSMakeRange(0, [str length]);
	[str replaceOccurrencesOfString: @"%l"
		withString: flist options: NSLiteralSearch range: range];

	return str;
}


@end


